package cn.zhibang.yygh2.service.hosp.service.impl;

import cn.zhibang.yygh2.service.client.service.cmn.client.DictFeignClient;
import cn.zhibang.yygh2.common.util.util.BeanUtils;
import cn.zhibang.yygh2.model.model.hosp.Hospital;
import cn.zhibang.yygh2.model.vo.hosp.HospitalQueryVo;
import cn.zhibang.yygh2.service.hosp.mapper.HospitalSetMapper;
import cn.zhibang.yygh2.service.hosp.repository.HospitalRepository;
import cn.zhibang.yygh2.service.hosp.service.DepartmentService;
import cn.zhibang.yygh2.service.hosp.service.HospitalService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    //自动装配repository.HospitalRepository，用来操作mongoDB
    @Autowired
    private HospitalRepository hospitalRepository;

    @Resource
    private HospitalSetMapper hospitalSetMapper;


    @Autowired
    private DictFeignClient dictFeignClient;

    @Autowired
    private DepartmentService departmentService;



    @Override
    public void save(Map<String, Object> paramMap) {
        //把参数map集合转换对象 Hospital医院对象
        //log.info(JSONObject.toJSONString(paramMap));
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);

        //1.判断是否存在数据(根据编号查询)
        String hoscode = hospital.getHoscode();
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hoscode);
        //在HospitalRepository中创建getHospitalByHoscode()方法（见下）

        //2.如果存在，进行修改
        if(null != targetHospital) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            //调用repository中的save()方法修改
            hospitalRepository.save(hospital);
            //如果继承了MongoRepository接口，Spring Data自动处理，使用save方法时，当主键在集合中存在时，会进行更新， 数据整体都会更新 ，新数据会替换掉原数据 ID 以外的所有数据。ID 不存在则新增一条数据

        } else { //3.如果不存在，进行添加
            hospital.setStatus(0); //0：已上线    1：未上线
            hospital.setCreateTime(new Date()); //获系统时间
            hospital.setUpdateTime(new Date()); //获系统时间
            hospital.setIsDeleted(0);
            //调用repository中的save()方法保存
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
//根据医院code，获得医院数据
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }


    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                //改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
// List<Hospital> content = pages.getContent(); //获得查询出来的数据
//获取查询list集合，遍历进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });
        return pages;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Map<String, Object> show(String id) {
        //准备Map封装数据
        Map<String, Object> result = new HashMap<>();
        //根据id获得医院信息（mongodb）
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        //将医院信息封装到map
        result.put("hospital", hospital);
        //提取出医院规则（单独处理更直观）
        result.put("bookingRule", hospital.getBookingRule());
        //设置医院规则为空（不需要重复返回）
        hospital.setBookingRule(null);
        return result;

    }

    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(null != hospital) {
            return hospital.getHosname();
        }
        return "";
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        //调用repository包中的方法，访问MongoDB中的医院数据
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }


    /**
     * 封装数据
     * @param hospital
     * @return
     */
    private Hospital packHospital(Hospital hospital) {
        //通过service-cmn-client中的Feign远程调用service-cmn服务中的方法
        //（1）根据dictCode和value获取医院等级名称
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        //（2）获得对应的省市区
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        //Hospital类中有个param的属性
        hospital.getParam().put("hostypeString", hostypeString);
        //将省市区拼接好后，也放入Hospital为的param中
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }



}
